using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

// 导出建筑位置数据为lua文件 ... 废弃啦
[ExecuteInEditMode]
public class BuildingTranformExporter : MonoBehaviour {

    public Material CitySpriteMat;

    private const string configPath = "/../Lua/modules/city/config/";

    public void SpawnConfig () {
#if UNITY_EDITOR
        string path = Application.dataPath + configPath;

        string filePath = path + "BuildTransformConfig.lua";
        if (!Directory.Exists (path)) {
            Directory.CreateDirectory (path);
        }

        var allSpriteRenderer = GetComponentsInChildren<SpriteRenderer> (true);

        StringBuilder sb = new StringBuilder ();
        sb.AppendLine ("return {");

        foreach (var spriteRenderer in allSpriteRenderer) {
            sb.AppendLine (string.Format ("[\"{0}\"] = {{", spriteRenderer.sprite.name));

            var localPosition = spriteRenderer.transform.localPosition;
            sb.AppendLine (string.Format ("position = {{x = {0},y = {1},z = {2}}},",
                localPosition.x.ToString ("F4"),
                localPosition.y.ToString ("F4"),
                localPosition.z.ToString ("F4")));

            var localEulerAngles = spriteRenderer.transform.localEulerAngles;
            sb.AppendLine (string.Format ("rotation = {{x = {0},y = {1},z = {2}}},",
                localEulerAngles.x.ToString ("F4"),
                localEulerAngles.y.ToString ("F4"),
                localEulerAngles.z.ToString ("F4")));

            var localScale = spriteRenderer.transform.localScale;
            sb.AppendLine (string.Format ("scale = {{x = {0},y = {1},z = {2}}},",
                localScale.x.ToString ("F4"),
                localScale.y.ToString ("F4"),
                localScale.z.ToString ("F4")));

            sb.AppendLine ("},");
        }

        sb.AppendLine ("}");

        StreamWriter streamWriter = new StreamWriter (filePath);
        streamWriter.Write (sb.ToString ());
        streamWriter.Flush ();
        streamWriter.Close ();

        AssetDatabase.Refresh ();
        Debug.Log ("导出建筑Transform数据成功：" + filePath);
#endif

    }

    public void ReplaceMat () {
#if UNITY_EDITOR
        if (CitySpriteMat == null)
        {
            return;
        }

        var allSpriteRenderer = GetComponentsInChildren<SpriteRenderer> (true);
        foreach (var spriteRenderer in allSpriteRenderer) {
            spriteRenderer.material = CitySpriteMat;
        }
#endif
    }
}



